//
//  NetworkTools.swift
//  WB
//
//  Created by leador on 17/4/1.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType:String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    //let 保证是线程安全的 swift中的单例
    static let shareInstance:NetworkTools = {
        
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools

    }()
    
}

//MARK: ---封装请求的方法---
extension NetworkTools {
    
    func request(methodType:RequestType,urlString:String,parameters:[String:AnyObject],finished:@escaping(_ result:AnyObject?,_ error:NSError?)->()) {
        
        let successCall = { (task:URLSessionDataTask?, result:Any) in
            finished(result as AnyObject?,nil)
        }
        
        let failCall = { (task:URLSessionDataTask?, error:Error) in
            finished(nil,error as NSError?)
        }
        
        if methodType == .GET {
            
            get(urlString, parameters: parameters, progress: nil, success: successCall, failure: failCall)
            
        }
        
        if methodType == .POST {
            
            post(urlString, parameters: parameters, progress: nil, success: successCall, failure: failCall)
            
        }

    }
    
}

//MARK: ---请求accessToken---
extension NetworkTools {
    
    func loadAccessToken(code:String,finished:@escaping (_ userAccount:UserAccount)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameter = ["client_id":app_key,"client_secret":app_secrect,"rant_type":"authorization_code","code":code,"redirect_uri":app_url]
        
        request(methodType: .POST, urlString: urlString, parameters: parameter as [String : AnyObject]) { (result, error) in
            
            if error != nil {
                return
            }
            
            guard let accountDict = result else {
                print("没有获取到授权的数据")
                return
            }
            
            let account = UserAccount(dict: accountDict as! [String : AnyObject])
            
            finished(account)
        
        }
        
    }
}

//MARK: ---请求用户信息---
extension NetworkTools {
    
    func loadUserInfo(accessToken:String,uid:String,finished:@escaping (_ result:[String:AnyObject]?,_ error:Error?)->()) {
    
        let urlString = "https://api.weibo.com/2/users/show.json"
    
        let parameter = ["access_token":accessToken,"uid":uid]
        
        request(methodType: .GET, urlString: urlString, parameters: parameter as [String : AnyObject]) { (result, error) in
            
            finished(result as! [String : AnyObject]?,error)
            
        }
    
    }
}

//MARK: ---请求首页数据---
extension NetworkTools {
    
    func loadStatuses(since_id:Int, max_id:Int,finished:@escaping (_ result:[[String:AnyObject]]?,_ error:NSError?)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let access_token = (UserAccountViewModel.shareInstance.account?.access_token)!
        let parameter = ["access_token":access_token,"since_id":"\(since_id)","max_id":"\(max_id)"]
        
        request(methodType: .GET, urlString: urlString, parameters: parameter as [String : AnyObject]) { (result, error) in
            
            guard let resultDic = result as? [String : AnyObject] else {
                finished(nil,error)
                return
            }
            
            finished(resultDic["statuses"] as! [[String : AnyObject]]?,error)
            
        }
        
    }

}

//MARK: ---发送微博---
extension NetworkTools {
    
    func sendStatus(statusText:String, isSuccess:@escaping (_ isSuccess:Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let access_token = (UserAccountViewModel.shareInstance.account?.access_token)!
        let parameter = ["access_token":access_token,"status":statusText]
        
        request(methodType: .POST, urlString: urlString, parameters: parameter as [String : AnyObject]) { (result, error) in
            
            if result != nil {
                isSuccess(true)
            }else {
                isSuccess(false)
            }
            
        }
    }
    
    
    func sendStatus(statusText:String, image:UIImage,isSuccess:@escaping (_ isSuccess:Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        
        let access_token = (UserAccountViewModel.shareInstance.account?.access_token)!
        
        let parameter = ["access_token":access_token,"status":statusText] as [String : Any]
        
        post(urlString, parameters: parameter, constructingBodyWith: { (formData) in
            
            if let imageData = UIImageJPEGRepresentation(image, 0.6) {
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
            }
            
        }, progress: nil, success: { (_, _) in
            isSuccess(true)
        }) { (_, error) in
            print(error)
            isSuccess(false)
        }
    }
    
    
}





